package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.mapper.SysMenuBackMapper;
import com.caifu.mapper.SysRoleMapper;
import com.caifu.mapper.SysRoleMenuBackMapper;
import com.caifu.mapper.SysUserBackMapper;
import com.caifu.pojo.*;
import com.caifu.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author tww
 * @since 2021-03-11
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysRoleMenuBackMapper roleMenuMapper;
    @Resource
    private SysMenuBackMapper menuMapper;

    @Resource
    private SysUserBackMapper userMapper;


    @Override
    public Result save(int userNo, String roleNo, String roleName, String roleDesc, String menuArr) throws Exception {
        SysUserBack user = new SysUserBack();
        SysRole role = new SysRole();
        try {

            user = userMapper.selectOne(new QueryWrapper<SysUserBack>().eq("user_no", userNo));
            if (user == null) {
                throw new Exception("在SysUser表中找不到用户信息");
            }

            if (StringUtils.isBlank(roleNo)) {
                //添加角色
                role = new SysRole();
                role.setName(roleName);
                role.setRoleDesc(roleDesc);
                role.setSort(999);
                role.setPreinstall("0");
                role.setState("1");
                role.setCreatedTime(new Date());
                roleMapper.insert(role);

                //更新授权
                String arr[] = arrDisitinct(menuArr);
                for (String str : arr) {
                    SysRoleMenuBack menu = new SysRoleMenuBack();
                    SysMenuBack sysMenu = menuMapper.selectById(Integer.parseInt(str));
                    SysMenuBack sysMoudelMenu = menuMapper.selectById(sysMenu.getParentNo());
                    SysMenuBack appMenu = menuMapper.selectById(sysMoudelMenu.getParentNo());
                    menu.setRoleId(role.getId());
                    menu.setMenuId(Integer.parseInt(str));
                    menu.setCreatedTime(new Date());
                    menu.setAppMenuId(appMenu.getParentNo());
                    roleMenuMapper.insert(menu);
                }

                //日志记录  sys 组织架构模块  sys-300 角色添加 sys-301 角色修改
                SysLog log = new SysLog(userNo, user.getPostType(), "sys", "sys-300", "1", user.getLoginName() + "新增角色成功[roleNo=" + role.getId() + ", roleName=" + role.getName() + "]！", new Date());
                return ResultUtil.retLog(200, "添加成功！", log);
            } else {
                role = roleMapper.selectOne(new QueryWrapper<SysRole>().eq("id", roleNo));
                role.setName(roleName);
                role.setRoleDesc(roleDesc);
                role.setUpdatedTime(new Date());
                roleMapper.updateById(role);

                //更新授权
                roleMenuMapper.delete(new QueryWrapper<SysRoleMenuBack>().eq("role_id", roleNo));
                String arr[] = arrDisitinct(menuArr);
                for (String str : arr) {
                    SysRoleMenuBack menu = new SysRoleMenuBack();
                    SysMenuBack sysMenu = menuMapper.selectById(Integer.parseInt(str));
                    SysMenuBack sysMoudelMenu = menuMapper.selectById(sysMenu.getParentNo());
                    SysMenuBack appMenu = menuMapper.selectById(sysMoudelMenu.getParentNo());
                    menu.setRoleId(role.getId());
                    menu.setMenuId(Integer.parseInt(str));
                    menu.setCreatedTime(new Date());
                    menu.setAppMenuId(appMenu.getParentNo());
                    roleMenuMapper.insert(menu);
                }

                //日志记录  sys 组织架构模块  sys-300 角色添加 sys-301 角色修改
                SysLog log = new SysLog(userNo, user.getPostType(), "sys", "sys-301", "1", user.getLoginName() + "修改角色成功[roleNo=" + role.getId() + ", roleName=" + role.getName() + "]！", new Date());
                return ResultUtil.retLog(200, "修改成功！", log);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //日志记录  sys 组织架构模块  sys-300 角色添加 sys-301 角色修改
            if (StringUtils.isBlank(roleNo)) {
                SysLog log = new SysLog(userNo, user.getPostType(), "sys", "sys-300", "9", user.getLoginName() + "添加角色失败[roleNo=" + role.getId() + ", roleName=" + role.getName() + "]！", new Date());
                return ResultUtil.retLog(199, "添加失败！", log);
            } else {
                SysLog log = new SysLog(userNo, user.getPostType(), "sys", "sys-301", "9", user.getLoginName() + "修改角色失败[roleNo=" + role.getId() + ", roleName=" + role.getName() + "]！", new Date());
                return ResultUtil.retLog(199, "修改失败！", log);
            }

        }
    }


    //去重
    private static String[] arrDisitinct(String arr) {
        if (arr.length() > 0) {
            arr = arr.substring(0, arr.length() - 1);
            String[] test1 = arr.split("\\|");
            ArrayList list = new ArrayList();
            for (int i = 0; i < test1.length; i++) {
                if (!list.contains(test1[i])) {
                    list.add(test1[i]);
                }
            }
            String str = list.toString().replaceAll("\\[", "").replaceAll("\\]", "") + ",";
            return str.replaceAll(" ", "").split(",");
        } else {
            return null;
        }

    }


}
